const jwt = require('jsonwebtoken')
//不能引，可能因为没有表。。。sync失败
// const sequelize =require("./db")
const { access_security, refresh_security } = require('../config/index')
const { cookieMaxAge } = require('../config/index')
const { TokenExpired, TokenNoFormat, ParameterError, RefreshTokenExpired } = require('../config/errorCode')
// 自定义错误
class CustomError extends Error {
  /**
     *
     * msg:错误消息
     * code:错误码
     */
  constructor (msg = '', code = '400') {
    super(msg)
    this.msg = msg
    this.code = code
  }
}
// 成功统一返回格式
const Success = (ctx, result = '') => {
  ctx.body = {
    code: 200,
    msg: 'ok',
    result
  }
  ctx.status = 200
}
// 生成token
const generateToken = (uid) => {
  return jwt.sign({
    uid
  }, access_security.secretKey, {
    expiresIn: access_security.expiresIn
  })
}
// 生成 refresh token
const generateRefreshToken = (uid) => {
  return jwt.sign({
    uid
  }, refresh_security.secretKey, {
    expiresIn: refresh_security.expiresIn
  })
}
// 校验token
const tokenIsValid = (token) => {
  let decode = null
  try {
    decode = jwt.verify(token, access_security.secretKey)
  } catch (error) {
    if (error.name == 'TokenExpiredError') {
      throw new CustomError('token已过期', TokenExpired)
    } else if (error.name == 'JsonWebTokenError') {
      throw new CustomError('token不合法', TokenNoFormat)
    } else {
      throw new CustomError('token校验未知错误', ParameterError)
    }
  }
  return decode
}
// 校验refresh token
const refreshTokenIsValid = (token) => {
  let decode = null
  try {
    decode = jwt.verify(token, refresh_security.secretKey)
  } catch (error) {
    if (error.name == 'TokenExpiredError') {
      throw new CustomError('refreshToken已过期', RefreshTokenExpired)
    } else if (error.name == 'JsonWebTokenError') {
      throw new CustomError('token不合法', TokenNoFormat)
    } else {
      throw new CustomError('token校验未知错误', ParameterError)
    }
  }
  return decode
}

const setCookie = (ctx, key, value) => {
  ctx.cookies.set(key, value, {
    // 过期时间 单位S
    maxAge: cookieMaxAge,
    // 客户端 JavaScrip无法获取cookie
    httpOnly: false,
    // 只有当前网页的 URL 与请求目标一致，才会带上 Cookie。
    sameSite: true,
    // 使用签名密钥，防止篡改
    signed: true,
    // 表示是否覆盖以前设置的同名的 cookie
    overwrite: true
  })
}
module.exports = {
  CustomError,
  Success,
  generateToken,
  generateRefreshToken,
  tokenIsValid,
  refreshTokenIsValid,
  setCookie
}
